package edu.govschool2010.screens;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;

public class MapScreen extends MapActivity {
    /** Called when the activity is first created. */
	LinearLayout linearLayout;
	MapView mapView;
	List<Overlay> mapOverlays;
	Drawable drawable;
	MapItemizedOverlay itemizedOverlay;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        mapOverlays = mapView.getOverlays();
        drawable = this.getResources().getDrawable(R.drawable.androidmarker);
        itemizedOverlay = new MapItemizedOverlay(drawable);
        final MapController mapControl = mapView.getController(); 
        mapControl.setZoom(3);
        
        final ImageButton ib = (ImageButton) findViewById(R.id.SearchButton);
        final Geocoder coder = new Geocoder(this);
        ib.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				EditText et = (EditText) findViewById(R.id.SearchEditText);
				String search = et.getText().toString();
				
				try {
					List<Address> geocodeResults = coder.getFromLocationName(search, 3);
					Iterator<Address> locations = geocodeResults.iterator();
					String locInfo = "Results:\n";
					
					while (locations.hasNext()) {
						Address loc = locations.next();
						int lat = (int)(loc.getLatitude()*1E6);
						int lon = (int)(loc.getLongitude()*1E6);
						
						locInfo += String.format("Locations: %f, %f", 
								loc.getLatitude(), loc.getLongitude());
						
						GeoPoint point = new GeoPoint(lat,lon);
				        OverlayItem overlayitem = new OverlayItem(point, "", "");
				        itemizedOverlay.addOverlay(overlayitem);
				        mapOverlays.add(itemizedOverlay);
				        mapControl.animateTo(point);				        
					}
					Log.i("Search", locInfo);
				} catch (IOException e) {
					Log.e("GeoAddress", "Failed to get location info", e);
				}
			}
		});
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

}